<template>
	<view class="w-full">
		<up-picker :show="show" :columns="[columns]" keyName="name" :defaultIndex="defaultIndex" @cancel="show = false" @confirm="handleConfirm"></up-picker>
		<view class="radius u-border flex items-center" @click="handleShow">
			<slot :value="valueName">
				<view class="value flex-1">{{ valueName }}</view>
				<up-icon name="arrow-down" color="#999" size="14"></up-icon>
			</slot>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const prop = defineProps({
	value: {
		type: Number,
	},
  placeholder: {
		type: String,
		default: '请选择'
	},
  columns: {
    type: Array,
    default: () => [
      {
        id: 1,
        name: '注册会员'
      },
      {
        id: 2,
        name: '待审核'
      },
      {
        id: 3,
        name: '已拉黑'
      },
    ]
  }
})
const emit = defineEmits(['update:value', 'confirm']);

const show = ref(false);

const innerValue = computed({
	get() {
		return prop.value
	},
	set(val) {
		emit('update:value', val)
	}
});

const defaultIndex = computed(() => {
	const index = prop.columns.findIndex(item => item.id == innerValue.value)

	if(index < 0) {
		return [0]
	}
  return [index];
});

const valueName = computed(() => {
	if(!prop.columns) return prop.placeholder
	const item = prop.columns.find(item => item.id == innerValue.value);
	if(!item) return prop.placeholder
  return item.name;
});


function handleShow() {
	if(prop.columns.length==0) return
	show.value = true;
}

function handleConfirm(e) {
	show.value = false;
	innerValue.value = e.value[0].id
}

</script>
<style lang="scss" scoped>
.radius {
	border-radius: 4px;
	padding: 10rpx 20rpx;
}
</style>